#!/usr/bin/env bash
################
dbus_daemon_fork() {
    if [ $(command -v sudo) ]; then
        sudo dbus-daemon --system --fork 2>/dev/null
    else
        su -c "dbus-daemon --system --fork 2>/dev/null"
    fi
}
###########
check_user_id_and_rm_dbus_pid() {
    case $(id -u) in
    0)
        rm -vf /var/run/dbus/pid 2>/dev/null
        dbus_daemon_fork
        ;;
    *)
        if [ -e "/var/run/dbus/pid" ]; then
            if [ $(command -v sudo) ]; then
                sudo rm -vf /var/run/dbus/pid 2>/dev/null
            else
                su -c "rm -vf /var/run/dbus/pid 2>/dev/null"
            fi
        fi
        dbus_daemon_fork
        ;;
    esac
}
###########
check_dbus_daemon() {
    case ${TMOE_PROOT} in
    true) [[ -e "/etc/init.d/dbus" ]] || check_user_id_and_rm_dbus_pid ;;
    esac

    case ${TMOE_CHROOT} in
    true) check_user_id_and_rm_dbus_pid ;;
    false) ;;
    *)
        if [[ -e /etc/motd ]]; then
            if grep -q 'Linux Deploy' /etc/motd 2>/dev/null; then
                check_user_id_and_rm_dbus_pid
            fi
        fi
        ;;
    esac
}
################
show_dbus_status() {
    if [[ -e /var/run/dbus/pid ]]; then
        PID=$(head -n 1 /var/run/dbus/pid)
        cat <<-EOF
${GREEN}●${BLUE} dbus.service${RESET} - ${YELLOW}D-Bus System Message Bus${RESET}
     Loaded: loaded (/lib/systemd/system/dbus.service; static)
     Active: ${GREEN}active (running)${RESET}
TriggeredBy: ${GREEN}● ${BLUE}dbus.socket${RESET}
       Docs: man:dbus-daemon(1)
   Main PID: ${PID} (dbus-daemon)
     CGroup: /system.slice/dbus.service
EOF
    fi
}
################
check_dbus_daemon
show_dbus_status
